<template>
  <div class="flex justify-center items-center h-screen bg-gray-100">
    <div class="bg-white shadow-lg rounded-lg p-8 w-full max-w-md">
      <h2 class="text-2xl font-bold mb-4">文生图</h2>
      <form @submit.prevent="submitForm" class="space-y-4">
        <div>
          <label for="description" class="block font-medium mb-1 text-gray-400">描述画面内容:</label>
          <textarea
            id="description"
            v-model="description"
            class="border rounded-md px-3 py-2 w-full h-24 resize-none"
            required
          ></textarea>
        </div>
        <div>
          <label for="quantity" class="block font-medium mb-1 text-gray-400">绘制数量:</label>
          <input
            type="number"
            id="quantity"
            v-model="quantity"
            class="border rounded-md px-3 py-2 w-full"
            required
          />
        </div>
        <button
          type="submit"
          class="bg-blue-500 hover:bg-blue-600 text-white font-medium py-2 px-4 rounded-md w-full transition duration-300"
        >
          确定
        </button>
      </form>

      <div v-if="errorMessage" class="mt-4 p-4 bg-red-100 text-red-700 rounded">
        {{ errorMessage }}
      </div>

      <div v-if="imgs.length" class="mt-6">
        <h3 class="text-xl font-semibold mb-2">图片预览列表</h3>
        <div class="grid grid-cols-2 sm:grid-cols-3 gap-4">
          <div v-for="(img, index) in imgs" :key="img" class="relative">
            <img
              :src="img"
              :alt="`Image ${index + 1}`"
              @click="showFullImagePreview"
              class="w-full h-32 object-cover rounded-md shadow"
            />
          </div>
        </div>
      </div>
    </div>

    <div v-if="showProgressModal" class="fixed z-10 inset-0 overflow-y-auto bg-black bg-opacity-50">
      <div class="flex items-center justify-center min-h-screen">
        <div class="bg-white shadow-lg rounded-full p-8 w-64 h-64 flex items-center justify-center">
          <div class="relative w-full h-full">
            <svg class="w-full h-full" viewBox="0 0 100 100">
              <circle cx="50" cy="50" r="45" fill="none" stroke="#e5e7eb" stroke-width="8" />
              <circle
                cx="50"
                cy="50"
                r="45"
                fill="none"
                stroke="#3b82f6"
                stroke-width="8"
                stroke-linecap="round"
                :stroke-dasharray="circumference"
                :stroke-dashoffset="dashOffset"
                class="transition-all duration-300 ease-in-out"
                transform="rotate(-90 50 50)"
              />
            </svg>
            <div
              class="absolute inset-0 flex items-center justify-center text-4xl font-bold text-blue-500"
            >
              {{ progress }}s
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <div v-if="showImagePreview" class="fixed z-10 flex items-center justify-center inset-0 w-full h-full overflow-y-auto bg-white">
    
      <div class="w-full h-full box-border">
        <div class="flex justify-between p-4">
          <span>预览</span>
          <button
            @click="closeImagePreview"
            class="text-gray-500 hover:text-gray-700 focus:outline-none"
          >
            <svg
              class="h-6 w-6"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
            >
              <path
                stroke-linecap="round"
                stroke-linejoin="round"
                stroke-width="2"
                d="M6 18L18 6M6 6l12 12"
              />
            </svg>
          </button>
        </div>
        <div class="p-4 grid grid-cols-1 gap-4">
          <div v-for="(img, index) in imgs" :key="img" class="relative flex justify-center items-center">
            <img
              :src="img"
              class="shadow max-w-full max-h-full"
              :alt="`Image ${index + 1}`"
            />
          </div>
        </div>
      </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'

const description = ref('')
const quantity = ref(0)
const imgs = ref([])
const showImagePreview = ref(false)
let interval = 0

const showFullImagePreview = () => {
  showImagePreview.value = true
}

const closeImagePreview = () => {
  showImagePreview.value = false
}
const showProgressModal = ref(false)
const progress = ref(0)
const errorMessage = ref('')

const circumference = 2 * Math.PI * 45
const dashOffset = computed(() => {
  return circumference * (1 - progress.value / 100)
})

const loadFromLocalStorage = () => {
  const savedDescription = localStorage.getItem('description')
  const savedQuantity = localStorage.getItem('quantity')
  const savedImgs = localStorage.getItem('imgs')

  if (savedDescription) description.value = savedDescription
  if (savedQuantity) quantity.value = Number(savedQuantity)
  if (savedImgs) imgs.value = JSON.parse(savedImgs)
}

onMounted(() => {
  loadFromLocalStorage()
})

const submitForm = async () => {
  showProgressModal.value = true
  progress.value = 0
  errorMessage.value = ''

  const workflowURL = 'https://api.coze.cn/v1/workflow/run'
  const requestData = {
    // 这里放入你的请求参数，具体根据工作流的要求来定
    parameters: {
      txt: description.value,
      num: quantity.value,
    },
    workflow_id: '7443409362439307275',
  }

  try {
    setTimeout(() => {
      let count = 0
      interval = setInterval(() => {
        count += 0.1
        progress.value = count.toFixed(1)
      }, 100)
    }, 500)

    const response = await fetch(workflowURL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization:
          'Bearer pat_uGCOzN8QUDTeRD8WA0H0t7K6KRsfFsJPFFPeO0eVQhT4eSHOvD7S7YjysLNlij6A',
      },
      body: JSON.stringify(requestData),
    })

    clearInterval(interval)
    showProgressModal.value = false

    if (!response.ok) {
      errorMessage.value = `HTTP error! status: ${response.status}`
      return
    }

    const data = await response.json()
    console.log(data)
    if (data.code == 0) {
      const result = JSON.parse(data.data)
      console.log('result', result)
      imgs.value = [...result.output]
      saveToLocalStorage()
    }
  } catch (error) {
    errorMessage.value = `Error calling workflow: ${error.message}`
    showProgressModal.value = false
    progress.value = 0
  }
}

const saveToLocalStorage = () => {
  localStorage.setItem('description', description.value)
  localStorage.setItem('quantity', quantity.value)
  localStorage.setItem('imgs', JSON.stringify(imgs.value))
}
</script>
